import { getCurrentInstance, onBeforeUnmount, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import page from './page.ts';
export function useListComponent(props: any = {}) {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  //页面信息
  const options: any = reactive({
    state: [
      {
        label: '待确认',
        value: 0,
        type: 'info',
      },
      {
        label: '已确认',
        value: 1,
        type: 'success',
      },
      {
        label: '已作废',
        value: -1,
        type: 'warning',
      },
      {
        label: '拒绝出库',
        value: -2,
        type: 'danger',
      },
    ],
    outStockState: [
      {
        label: '待出库',
        value: 0,
        type: 'info',
      },
      {
        label: '已出库',
        value: 1,
        type: 'success',
      },
    ],
    courierFeeReconciliationStatus: [
      {
        label: '待对账',
        value: 0,
        type: 'info',
      },
      {
        label: '已对账',
        value: 1,
        type: 'success',
      },
    ],
    customer: [], //客户
    receivingWay: [], //收货方式
    expressWay: [], //快递方式
    paymentWay: [], //付费方式
    costAssumeDepartment: [], //费用部门
    treeArea: [], //地址信息
    product: [], //产品订单信息
  });
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    warehouseCode: '', //仓库code
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'deliveryBillNo',
      theadCode: 'saleOrderDeliverylist', //basedatatable
      //表格-表头数据
      thead: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: '', // 关键字查询字段，空值表示查询全部
        likeWords: '', // 查询关键字，空值表示不进行过滤
        beginTime: '', // 查询时间范围起始值（建议格式：yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss）
        endTime: '', // 查询时间范围结束值
        onlySelf: 0, // 是否只查自己创建的数据：0 查所有；1 只查自己
        isShowDisabled: -1, // 是否显示禁用/作废数据：-1 所有；0 未作废；1 仅作废
        orderByFiled: '', // 排序字段名称，如 createTime、updateTime 等
        orderByType: 0, // 排序方式：0 倒序；1 升序
        //差异
        receivingWay: '', //收货方式
        expressWay: '', //送货方式
        paymentWay: '', //付款方式
        deliveryBillState: -5, // 发货单状态：0待确认；1已确认；-1已作废；-2拒绝出库，-5查询全部
        outStockState: -1, // 出库状态：0待出库；1已出库；-1查询全部
        courierFeeReconciliationStatus: -1, // 快递费用对账状态,-1 查全部、0-未对账、1-已对账
        ...props.query,
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.OrderBusniess.GetMatchPageSaleOrderDeliveryList({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 10000,
                  beginTime: dataInfo.table.search.beginTime || proxy.$getTimeAgo(1, 'years'), // 开始时间
                  endTime: dataInfo.table.search.endTime || proxy.$day(new Date()), // 结束时间
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
        {
          title: '批量导出明细',
          icon: '',
          type: '',
          click: () => {
            const _checkbox = dataInfo.table.checkbox.list;
            if (_checkbox.length === 0) {
              proxy.$message('请勾选要导出的数据', 'error');
              return;
            }
            const _tbody: any[] = [];
            _checkbox.forEach((el: any) => {
              if (el.detailList?.length > 0) {
                el.detailList.forEach((row: any) => {
                  _tbody.push({
                    ...el,
                    ...row,
                    createTime: proxy.$day(row.createTime),
                    produceDate: proxy.$day(row.produceDate),
                  });
                });
              }
            });
            proxy.$exportData(
              {
                thead: [
                  {
                    label: '发货日期',
                    prop: 'createTime',
                    align: 'center',
                    width: 120,
                  },
                  {
                    label: '生产日期',
                    prop: 'produceDate',
                    align: 'center',
                    width: 120,
                  },
                  {
                    label: '客户',
                    prop: 'customerName',
                    align: 'left',
                    width: 160,
                  },
                  {
                    label: '协议书号',
                    prop: 'xieYiShuHao',
                    align: 'center',
                    width: 120,
                  },
                  {
                    label: '产品名称',
                    prop: 'productName',
                    align: 'left',
                    width: 120,
                  },
                  {
                    label: '尺寸',
                    prop: 'size',
                    align: 'left',
                    width: 160,
                  },
                  {
                    label: '发货数量',
                    prop: 'deliveryQuantity',
                    align: 'center',
                    width: 120,
                  },
                ],
                tbody: _tbody,
                fileName: dataInfo.table.title,
              },
              dataInfo,
            );
          },
        },
        {
          title: '批量发货',
          icon: 'Plus',
          type: 'primary',
          click: () => {
            getPath({
              path: `${route.path}/add`,
              query: {
                type: 1, //页面类型
              },
            });
          },
        },
        {
          title: '单独发货',
          icon: 'Plus',
          type: 'primary',
          click: () => {
            getPath({
              path: `${route.path}/details`,
              query: {
                type: 1, //页面类型
              },
            });
          },
        },
      ],
      //表格-列表搜索
      operation: [
        {
          title: '查看',
          hidden: (row: any) => {
            return row.deliveryBillState === 0;
          },
          click: (row: any) => {
            getPath({
              path: `${route.path}/details`,
              query: {
                type: 3, //页面类型
                code: row.deliveryBillNo, //单号
              },
            });
          },
        },
        {
          title: '编辑',
          hidden: (row: any) => {
            return row.deliveryBillState !== 0;
          },
          click: (row: any) => {
            getPath({
              path: `${route.path}/details`,
              query: {
                type: 2, //页面类型
                code: row.deliveryBillNo, //单号
              },
            });
          },
        },
        {
          title: '确认',
          disabled: (row: any) => {
            return ![0].includes(row.deliveryBillState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否确认当前数据，请确认！', () => {
              proxy.$api.OrderBusniess.SureSaleOrderDelivery({
                entityID: row.deliveryID,
              })
                .then((res: any) => {
                  proxy.$message('确认');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '撤回',
          disabled: (row: any) => {
            return ![1].includes(row.deliveryBillState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否撤回当前数据，请确认！', () => {
              proxy.$api.OrderBusniess.RevokeSaleOrderDelivery({
                entityID: row.deliveryID,
              })
                .then((res: any) => {
                  proxy.$message('撤回');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '发货',
          children: [
            {
              title: '打印',
              disabled: (row: any) => {
                return [0].includes(row.getMaterialBillState);
              },
              click: (row: any) => {
                proxy.$DownLoadTemp(
                  {
                    templateTypeCode: 'MBLX0006', //	模板类型编号
                    customerCode: row.customerCode, //	客户编号
                    condition: {
                      DeliveryBillNo: row.deliveryBillNo,
                    },
                  },
                  1,
                  dataInfo,
                );
              },
            },
            {
              title: '下载',
              disabled: (row: any) => {
                return [0].includes(row.getMaterialBillState);
              },
              click: (row: any) => {
                proxy.$DownLoadTemp(
                  {
                    templateTypeCode: 'MBLX0006', //	模板类型编号
                    customerCode: row.customerCode, //	客户编号
                    condition: {
                      DeliveryBillNo: row.deliveryBillNo,
                    },
                  },
                  3,
                  dataInfo,
                );
              },
            },
          ],
        },
        {
          title: '删除',
          disabled: (row: any) => {
            return ![0].includes(row.deliveryBillState);
          },
          click: (row: any) => {
            proxy.$messageBox('是否删除当前数据，请确认！', () => {
              proxy.$api.OrderBusniess.DeleteSaleOrderDelivery({
                entityID: row.deliveryID,
              })
                .then((res: any) => {
                  proxy.$message('删除成功');
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
      ],
    },
  });
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    // 在新窗口或标签页中打开目标路径
    const newWindow: any = window.open(path.href, '_blank');
    newWindow;
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.OrderBusniess.GetMatchPageSaleOrderDeliveryList({
      ..._table.search,
      warehouseCode: dataInfo.warehouseCode,
    })
      .then((res: any) => {
        _table.tbody = res.list.map((el: any) => ({
          ...el,
          productName: el.detailList.map((el: any) => el.productName).join('、'),
          xieYiShuHao: el.detailList.map((el: any) => el.xieYiShuHao).join('、'),
        }));
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[], thead?: any[]) => {
    proxy.$exportData(
      {
        thead: thead || dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };

  onMounted(() => {});
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, options };
}
